package seatiger.tomcat.catalina.core;

import seatiger.tomcat.catalina.*;
import seatiger.tomcat.catalina.connector.NewRequest;
import seatiger.tomcat.catalina.connector.NewResponse;
import seatiger.tomcat.util.StringManager;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Host 容器中对应的基础阀
 */
public class StandardHostValve extends ValveBase {

    private static final String info =
            "seatiger.tomcat.catalina.core.StandardHostValve/1.0";

    private static final StringManager sm =
            StringManager.getManager(Constants.PACKAGE_CORE);

    @Override
    public String getInfo() {
        return info;
    }

    @Override
    @Deprecated
    public void invoke(Request request, Response response, ValveContext context) throws IOException, ServletException {
        if (!(request.getRequest() instanceof HttpServletRequest) ||
                !(response.getResponse() instanceof HttpServletResponse)) {
            return;
        }
        //获取容器
        StandardHost host = (StandardHost) getContainer();
        //获取容器对应的映射器
        Container container = host.map(request, true);
        if (context == null) {
            ((HttpServletResponse) response.getResponse()).sendError
                    (HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            sm.getString("standardHost.noContext"));
            return;
        }
        container.invoke(request, response);
    }

    @Override
    public void invoke(NewRequest request, NewResponse response) throws IOException, ServletException {
        Context context = request.getContext();
        context.getPipeline().getFirst().invoke(request,response);
    }
}
